package com.mspbots.teams.sync.schedule;

import com.mspbots.api.client.CoreClient;
import com.mspbots.teams.model.Tenant;
import com.mspbots.teams.sync.service.TeamsSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.Optional;

@Slf4j
@Component
@EnableScheduling
public class SyncTeams {

    @Autowired
    private CoreClient coreClient;
    @Autowired
    private TeamsSyncService teamsSyncService;

    //    @Scheduled(initialDelay=5 * 60 * 1000, fixedDelay=60 * 60 * 1000)
    private void syncUser() {
        Optional<List<Tenant>> tenantsOpt = this.coreClient.getFlux("tenant/active", null, Tenant.class).collectList().blockOptional(Duration.ofSeconds(5));
        for (Tenant tenant : tenantsOpt.get()) {
            log.debug("tenant start sync teams user{}", tenant);
            teamsSyncService.autoSyncUsers(tenant.getId()).subscribe();
        }
    }
}
